//
//  SubmitOrderVc.m
//  Courses
//
//  Created by YiXuePxh on 15/4/20.
//  Copyright (c) 2015年 boyibang. All rights reserved.
//

#import "SubmitOrderVc.h"
#import "WTFRect.h"
#import "WTFColors.h"
#import "ConfirmBillVc.h"

#import "AliOrder.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Product.h"
#import "APAuthV2Info.h"
#import "SubmitOrderVc.h"


#import "PlayBgin.h"
#import "PayEndData.h"

#import "PayEndViewController.h"
@interface SubmitOrderVc ()<UIAlertViewDelegate>

@end

#define RATIO 5

@implementation SubmitOrderVc
{
    PlayBgin* _playBegin;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
}
-(id)initWith:(SubmitOrder* )order Page:(int)page{
    if (self = [super init]) {
        _order = order;
        _page = page;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"支付";
    //将实付金额赋值
    _realMount = [_order.realAmount floatValue];
    if (_page == 1) {
        _pay = nil;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            _pay = [SubmitPay getOrderWithSubmitOrder:_order];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showOrderMessage];
            });
        });
    }else{
        [self showOrderMessage];
    }
    UILabel* orderShow = [[UILabel alloc]initWithFrame:AutoRectMake(10, 10, 200, 30, WTFAutoLayoutTypeText)];
    [self.view addSubview:orderShow];
    orderShow.text = @"订单提交成功";
    orderShow.textColor = [UIColor orangeColor];
    orderShow.font = [UIFont fontWithName:nil size:22];
    //划线
    [self drawLine:45 + RATIO];
        //划线
    [self drawLine:110 + RATIO + 20];
    //支付按钮
    UIImageView* alipay = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AliPay.png"]];
    [self.view addSubview:alipay];
    [alipay setFrame:AutoRectMake(10, 120 + RATIO + 20, 58, 58, WTFAutoLayoutTypeBar)];
    alipay.contentMode = UIViewContentModeScaleAspectFit;
    
    UILabel* ali = [[UILabel alloc]initWithFrame:AutoRectMake(70, 120 + RATIO + 35, 70, 20, WTFAutoLayoutTypeText)];
    [self.view addSubview:ali];
    ali.text = @"支付宝";
    
    UIButton* aliBtn = [[UIButton alloc]initWithFrame:AutoRectMake(130, 115 + RATIO + 35, 100, 30, WTFAutoLayoutTypeBar)];
    [self.view addSubview:aliBtn];
    [aliBtn setTitle:@"在线支付" forState:UIControlStateNormal];
    aliBtn.titleLabel.text = @"在线支付";
    [aliBtn setBackgroundImage:[UIImage imageNamed:@"btnBg2"] forState:UIControlStateNormal];
    [aliBtn setBackgroundImage:[UIImage imageNamed:@"btnBg2"] forState:UIControlStateSelected];
    [aliBtn addTarget:self action:@selector(playBeginAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self drawLine:180 + RATIO + 25];
    
}

-(void)showOrderMessage{
    //orderNum
    UILabel* orderNum = [[UILabel alloc]initWithFrame:AutoRectMake(5, 50 + RATIO + 5, 400, 35, WTFAutoLayoutTypeText)];
    [self.view addSubview:orderNum];
    orderNum.text = [NSString stringWithFormat:@"订单编号 :%@",_pay.orderNo];
    orderNum.font = [UIFont fontWithName:nil size:12];
    //moblie
    UILabel* moblie = [[UILabel alloc]initWithFrame:AutoRectMake(5, 70 + RATIO + 5, 400, 35, WTFAutoLayoutTypeText)];
    [self.view addSubview:moblie];
    moblie.text = [NSString stringWithFormat:@"手机号码 :%@",_order.showPhoneNum];
    moblie.font = [UIFont fontWithName:nil size:12];
    //realMount
    UILabel* realMount = [[UILabel alloc]initWithFrame:AutoRectMake(5, 90 + RATIO + 5, 400, 35, WTFAutoLayoutTypeText)];
    [self.view addSubview:realMount];
    realMount.text = [NSString stringWithFormat:@"实付金额 :%.2f",_realMount];
    realMount.font = [UIFont fontWithName:nil size:12];

}
-(void)playBeginAction{
    if (_pay.orderId.length > 0) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            _playBegin = [PlayBgin getPlayBginWithAgencyid:_order.agencyId UserId:_order.userId Platform:@"ALIPAY" OrderId:_pay.orderId RealAmount:[NSString stringWithFormat:@"%.2f",_realMount]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self aliAction];
            });
        });
    }else{
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"订单信息" message:@"订单信息获取不成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}


-(void) drawLine: (float)hight{
    UIView* line = [[UIView alloc]initWithFrame:AutoRectMake(0, hight, DEFAULT_WIDTH, 1, WTFAutoLayoutTypeBar)];
    line.backgroundColor = [WTFColors defaultTextColor];
    [self.view addSubview:line];
}
-(void)aliAction{
    //
    //选中商品调用支付宝极简支付
    //
    /*
     *点击获取prodcut实例并初始化订单信息
     */
    //    Product *product = [self.productList objectAtIndex:indexPath.row];
    
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088111904884101";
    NSString *seller = @"luqi@yxcps.com";
    NSString *privateKey = @"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALY6wfi+HJCWdg+O+Mc3SyqoHjoSxDAJ4XBy8wLuyg9YfgN6klJLoKQ4KWhN9BwBN8hWPsIWFTWj7eOSy+H61jQc74/hgcolsFL3qWGIKgHkXoLH4JjQ9Y89wmV6sEl5c/+tqNDDIM752yZEh+Sv18a8AFtj30f376E1ulshBa13AgMBAAECgYBb2xRpmRL3AxDx2MSoTsPx9Zp+9XS1LlXYA+lhAhMSVy31/PQCzaJlBPZCYID7GNYQgwDRfqYkSsSgIR/qgjE0a91lVEsSKcAa8qWN9ipYiAgotDy8VE7ScvEqRyP8zjH+aGEU9KVHodR9/MhZYaocRu1NSMP1WIEvs+XZO5EF+QJBANkVJjbVZBBGpVZW6wP1BDmsw8a7f3QXlaBczzxXs4frWGWBMDh+gOxdR+Ckna/PMfaLTAs+DyLs/brrhzgqnSUCQQDW5g0AlmMWBd5uBnXWL1/82P+nfzg+XUyC84W8K5fnFNuePRUeAmsC3ciunreu9LhRPFVArLSny+NFksTtR1NrAkAVT9A6neR+/JCK02mrL8jEaMOnpQy0NwSHg9UMlYeYlnBNNsunIDREADxoP4EDm5HKJI7Io8UUprOaQDk8OGLJAkAvC1+vUDzS1mgSOBHV2LsvtCWLentKk8wrIrqVLgnsCZHme0LDNg5NK1ZCe/aEM4iiKA4VwXku/qB7W50GwMWPAkBGdjZyR9LJ7Sf9qNsCehbdJm3gjwv9YqMtueVS0wha6r+ePyCvCsNaVck7BKfZqVTVWLRJmT4IZGee6D9LuxGh";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    AliOrder *order = [[AliOrder alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = _playBegin.paymentNo; //订单ID（由商家自行制定）
    //    order.productName = [NSString stringWithFormat:@"%@ %@",_course.courseName,timeArray[0]]; //商品标题
    order.productName = @"益学堂"; //商品标题
    order.productDescription = @"益学堂课程"; //商品描述
    //    order.amount = [NSString stringWithFormat:@"%.2f",product.price]; //商品价格
    order.amount = [NSString stringWithFormat:@"%.2f",0.01]; //商品价格  现在写死  goto
//    order.notifyURL =  _playBegin.notifyUrl; //回调URL   正式环境调用
    order.notifyURL = @"http://116.228.99.110:13145/paycall/alipayCallback";
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"支付宝 啦啦啦啦啦了 reslut = %@",resultDic);
            int status = [resultDic[@"resultStatus"] intValue];
            [self AlipayResultStatus: status];
        }];
    }
}
                
-(void)AlipayResultStatus:(int)resulstStatus{
    if (resulstStatus == 9000) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            PayEndData* payEnd = [PayEndData getPayDataBySourcId:@"2" DeciceNo:@"IOS12345" UserId:_order.userId OrderId:_pay.orderId PaymentNo:_playBegin.paymentNo TradeRtn:@"1" TradeId:@"20141230181921005" TradeAmount:[NSString stringWithFormat:@"%d",_realMount] TradeTime:@"2014"];
           dispatch_async(dispatch_get_main_queue(), ^{
               NSLog(@"%@",payEnd);
               PayEndViewController* payEndVc = [[PayEndViewController alloc]initWithNibName:@"PayEndViewController" bundle:nil];
               [self.navigationController pushViewController:payEndVc animated:NO];
           });
        });
    }else{
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"支付失败请重新支付！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
         
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        NSLog(@"确定按钮");
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
